package scau.gsmg.misp.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import scau.gsmg.misp.dao.BaseDAO;
import scau.gsmg.misp.dao.IGoodsDAO;
import scau.gsmg.misp.vo.Goods;
import scau.gsmg.misp.vo.GoodsType;

/**
 * @Title: GoodsDAO.java
 * @Group: GaoShenMenGui
 * @Author: WXY
 * @Date: 2015-4-4
 */
@Repository
public class GoodsDAO extends BaseDAO implements IGoodsDAO {

	/**
	 * Goods展示并且实现分页功能
	 */
	@Override
	public List getGoodsList(String page, String rows, String sort, String order)
			throws Exception {
		// TODO Auto-generated method stub

		String param = null;
		String hql = "from Goods g";
		hql = hql + " order by " + sort + " " + order;
		List dataList = new ArrayList();
		dataList = searchAllGoods(hql, param, page, rows);
		return dataList;
	}

	private List searchAllGoods(String hql, String name, String page,
			String rows) {
		Session session = getSession();
		List<Goods> goods = null;
		List dataList = new ArrayList();
		try {

			// 当为缺省值的时候进行赋值

			int currentpage = Integer
					.parseInt((page == null || page == "0") ? "1" : page);// 当page为空时，给page赋值1

			int pagesize = Integer
					.parseInt((rows == null || rows == "0") ? "10" : rows);// 每页多少行

			Query query = session.createQuery(hql);
			if (name != null) {
				query.setParameter(0, "%" + name + "%");
			}
			goods = query.setFirstResult((currentpage - 1) * pagesize)
					.setMaxResults(pagesize).list();
			for (Goods g : goods) {
				HashMap<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap.put("id", g.getId());
				jsonMap.put("barcode", g.getBarcode());
				jsonMap.put("typeName", g.getGoodsType().getName());
				jsonMap.put("tid", g.getGoodsType().getId());
				jsonMap.put("name", g.getName());
				jsonMap.put("purchasePrice", g.getPurchasePrice());
				jsonMap.put("price", g.getPrice());
				jsonMap.put("unit", g.getUnit());
				jsonMap.put("description", g.getDescription());

				dataList.add(jsonMap);
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("捕获异常：" + e);
		} finally {
			session.close();
		}
		return dataList;
	}

	/**
	 * 返回商品总数
	 */
	@Override
	public int getGoodsCount() throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		String hql = "from Goods g";
		try {
			Query query = session.createQuery(hql);
			List customer = query.list();
			int size = customer.size();
			return size;
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("捕获异常：" + e);
		} finally {
			session.close();
		}
		return 0;
	}

	/**
	 * 商品类型结点树combotree
	 */
	public List<GoodsType> combotree() {
		Session session = getSession();
		try {
			String hql = "from GoodsType g";
			Query query = session.createQuery(hql);
			List<GoodsType> list = query.list();
			session.close();
			return list;
		} catch (Exception e) {
			System.out.println("捕获异常：" + e);
			return null;
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
	}

	/**
	 * 增加商品
	 */
	@Override
	public boolean addGoods(Goods goods) {
		// TODO Auto-generated method stub
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		try {
			session.save(goods);
			tx.commit();
			return true;
		} catch (Exception e) {
			return false;
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
	}

	/**
	 * 更新商品
	 */
	@Override
	public boolean updateGoods(Goods goods) {
		// TODO Auto-generated method stub
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		try {
			session.update(goods);
			tx.commit();
			return true;
		} catch (Exception e) {
			System.out.println("捕获异常：ww" + e);
			return false;
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}

	}

	/**
	 * 删除商品
	 */
	@Override
	public boolean removeGoods(int id) {
		// TODO Auto-generated method stub
		boolean flag = false;
		Session session = getSession();
		try {
			String hql = "delete Goods g where g.id=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, id);
			query.executeUpdate();
			flag = true;
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		} finally {
			session.close();
		}
		return flag;
	}

	/**
	 * 更新商品
	 */
	@Override
	public boolean updateGoods(int id, String barcode, String type_id,
			String name, double purchase_price, double price,
			String description, String unit) {
		// TODO Auto-generated method stub

		int type = type(type_id);
		Goods goods = new Goods();
		GoodsType goodsType = new GoodsType();
		goodsType.setId(type);
		goods.setGoodsType(goodsType);
		goods.setId(id);
		goods.setBarcode(barcode);
		goods.setName(name);
		goods.setPurchasePrice(purchase_price);
		goods.setPrice(price);
		goods.setUnit(unit);
		goods.setDescription(description);

		Session session = getSession();
		Transaction tx = session.beginTransaction();
		try {
			session.update(goods);
			tx.commit();
			return true;
		} catch (Exception e) {
			System.out.println("捕获异常：ww" + e);
			return false;
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}

	}

	/**
	 * @Description:根据商品类型名字查询其id号
	 */
	private int type(String name) {
		Session session = getSession();
		int id = 1;
		String hql = "from GoodsType g where g.name=?";
		try {

			Query query = session.createQuery(hql);
			query.setParameter(0, name);
			List<GoodsType> list = query.list();
			for (GoodsType g : list) {
				id = g.getId();
				System.out.println("updateDAO" + id);
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("捕获异常：" + e);
		} finally {
			session.close();
		}
		return id;
	}

	/**
	 * @Description:搜索商品
	 */
	@Override
	public List searchGoods(String page, String rows, String barcode,
			String name, String typeName, String sort, String order) {
		// TODO Auto-generated method stub
		Session session = getSession();
		String param = null;
		String hql = "from Goods g";
		List dataList = new ArrayList();
		try {
			if (barcode != null) {
				hql = "from Goods g where g.barcode like ?";
				hql = hql + " order by " + sort + " " + order;
				name = barcode;
				dataList = searchAllGoods(hql, name, page, rows);
				return dataList;
			}
			if (name != null) {
				hql = "from Goods g where g.name like ?";
				hql = hql + " order by " + sort + " " + order;
				dataList = searchAllGoods(hql, name, page, rows);
				return dataList;
			}
			if (typeName != null) {
				hql = "from Goods g where g.goodsType.name like ?";
				hql = hql + " order by " + sort + " " + order;
				name = typeName;
				dataList = searchAllGoods(hql, name, page, rows);
				return dataList;
			}
			dataList = searchAllGoods(hql, param, page, rows);
		} catch (Exception e) {
			System.out.println("捕获异常：ww" + e);
			// return 0;
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}

		return dataList;
	}

	/**
	 * @Description:搜索出的商品总数
	 */
	@Override
	public int searchCount(String barcode, String name, String typeName) {
		// TODO Auto-generated method stub
		String hql = "";
		Session session = getSession();
		try {
			hql = "from Goods";
			if (barcode != null) {
				hql = "from Goods g where g.barcode like ?";
				Query query = session.createQuery(hql);
				query.setParameter(0, "%" + barcode + "%");
				return query.list().size();

			}
			if (name != null) {
				hql = "from Goods g where g.name like ?";
				Query query = session.createQuery(hql);
				query.setParameter(0, "%" + name + "%");
				return query.list().size();
			}
			if (typeName != null) {
				hql = "from Goods g where g.goodsType.name like ?";
				Query query = session.createQuery(hql);
				query.setParameter(0, "%" + typeName + "%");
				return query.list().size();
			}
			Query query = session.createQuery(hql);
			return query.list().size();
		} catch (Exception e) {
			System.out.println("捕获异常：searchCount " + e);
			// return 0;
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return 0;
	}
}
